<template>
  <div>
    <van-nav-bar left-arrow @click-left="leftClick"></van-nav-bar>
    <h4 class="title">短信登录</h4>
    <div class="form">
      <van-form ref="form">
        <!-- :rules="rules" -->
        <van-field
          v-model="form.mobile"
          :rules="rules.mobile"
          placeholder="请输入手机号"
          name="mobile"
        ></van-field>
        <van-field
          v-model="form.code"
          :rules="rules.code"
          placeholder="请输入验证码"
        >
          <template #button>
            <div
              @click="getCode"
              class="Code"
              name="sendCode"
              v-if="totalTime === 6"
            >
              发送验证码
            </div>
            <div v-else class="Code">{{ totalTime }}秒后再试</div>
          </template>
        </van-field>
        <van-button type="primary" class="btn" @click="submit">登录</van-button>
      </van-form>
    </div>
  </div>
</template>

<script>
import { authorizations, smsCodes } from '@/api/user.js'
export default {
  data () {
    return {
      interval: '',
      totalTime: 6,
      form: {
        mobile: '13200000000',
        code: '246810'
      },
      rules: {
        mobile: [
          { required: true, message: '必填', trigger: 'onChange' },
          {
            validator: value => {
              const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              return reg.test(value)
            },
            message: '请输入11位手机号',
            trigger: 'onChange'
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'onChange' },
          {
            validator: value => {
              return value.length === 6
            },
            message: '请输入6位验证码',
            trigger: 'onChange'
          }
        ]
      }
    }
  },
  beforeDestroy () {
    clearInterval(this.interval)
  },
  methods: {
    leftClick () {
      //   console.log('左箭头')
      this.$router.push('/')
    },
    getCode () {
      //   console.log('测试-获取验证码')
      //  验证手机号是否输入正确 给van-form 绑定ref属性
      this.$refs.form
        .validate('mobile') // 验证项：绑定手机号的name值
        .then(async () => {
          // 设置定时器
          this.totalTime-- // 定时器设置在1秒后启动，避免在这一秒前用户多次点击‘发送验证码’
          this.interval = setInterval(() => {
            this.totalTime--
            if (this.totalTime <= 0) {
              clearInterval(this.interval)
              //  还原时间
              this.totalTime = 6
              //  需求：避免用户在获取验证码途中，跳转了其他页面，而此时的定时器还在继续执行浪费了性能，在页面渲染前清除掉定时器
            }
          }, 1000)
          // 获取验证码
          await smsCodes(this.form.mobile)
          this.$toast.success('发送成功')
        })
      // .catch(() => {
      //   this.$toast.fail('验证失败') 已经做了统一错误处理就不需要写catch了
      // })
    },
    submit () {
      // 全局验证 给van-form 绑定ref属性
      this.$refs.form.validate().then(async () => {
        //   this.$toast.success('验证成功')
        this.$toast.loading({ duration: 2000 })
        const res = await authorizations(this.form)
        console.log('用户登录', res)
        //  存在token
        this.$store.commit('user/getState', res.data.token)
        this.$toast.success('登录成功')
        // 1、正常登陆跳转至首页 2、用户从需要登录的页面跳转出来的，登录回跳至相应的页面
        const path = this.$route.query.redirect || '/'
        this.$router.push(path)
      })
      // .catch(() => {
      //   this.$toast.fail('验证失败')
      // })
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .van-nav-bar .van-icon {
  color: #999;
}
.form {
  padding: 15px;
}
.title {
  font-weight: 400;
  padding: 20px;
}

.btn {
  margin-top: 15px;
  width: 100%;
}
.Code {
  color: #ccc;
}
</style>
